import { useState } from "react";
import { CheckOutlined, CopyOutlined } from "@ant-design/icons";

function CopyButton({ id }: { id: string }) {
  // 复制状态控制
  const [copied, setCopied] = useState(false);
  const handleCopy = async () => {
    try {
      setCopied(true);
      // 获取代码块文本
      const text = document.getElementById(id)!.innerText + `\n————————————————\n\n版权声明：本文为博主原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接和本声明。\n 原文链接：${window.location.href}`;
      // 复制到剪贴板
      await navigator.clipboard.writeText(text);
      // 复制成功后重置状态
      setTimeout(() => {
        setCopied(false);
      }, 1500);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <button
      onClick={handleCopy}
      className="inline-flex rounded-md p-2 absolute -right-3 -top-5"
    >
      <CopyOutlined
        size={16}
        className={`transition-all text-white ${copied ? "scale-0" : "scale-100"}`}
      />
      <CheckOutlined
        size={16}
        className={`absolute transition-all text-success ${copied ? "scale-100" : "scale-0"}`}
        style={{ color: "green" }}
      />
    </button>
  );
}

export { CopyButton };